<?php
namespace Pay\Service\Wxpay;

use Pay\Service\Wxpay\ActionAbstract;

//微信付款码支付
class Micropay extends ActionAbstract
{
    private $retmessage = [];

    /*
     * 如果没有参数config默认取自有的配置
     */
    public function __construct($config = false)
    {
        parent::__construct($config);
    }

    /*
     * 进行微信付款码支付
     * 一些必要参数$params如下:
     * $params['price']:价格
     * $params['auth_code']:付款码
     * $params['body']:支付信息,不能为空
     * $params['orderNumber']:订单编号,不能为空
     *
     * return 成功时返回true,请验证全等。失败时返回错误数组信息
     */
    public function doMicropay($params)
    {
        $params['nonceStr'] = \Pay\Service\Common\Randstr::human(16);
        return $this->SignPay($params);
    }

    /*
     * 获取微信的返回结果
     */
    public function getRet()
    {
        return $this->retmessage;
    }

    protected function SignPay($params)
    {
        if (!$params['auth_code'] || !$params['body']) {
            return false;
        }
        if (!$params['price'] || !$params['orderNumber']) {
            return false;
        }
        $scene = ['h5_info' => ['type' => 'h5_info', 'app_name' => $params['subject']]];
        $scene = json_encode($scene);
        $ip = \Pay\Service\Common\Ip::getClientIp();
        $param = [
            'appid' => $this->config['appIdWxa'],
            'mch_id' => $this->config['mchId'],
            'nonce_str'=> $params['nonceStr'],
            'body'=> $params['body'],
            'out_trade_no' => $params['orderNumber'],
            'auth_code' => $params['auth_code'],
            'total_fee'=> $params['price'],
            'spbill_create_ip' => $ip,
            'sign_type' => 'MD5',
            'scene_info'=> $scene,
        ];
        ksort($param);

        foreach ($param as $key => $value) {
            $str .= $key.'='.$value.'&';
        }
        $signStr = $str.'key='.$this->config['key'];
        $sign = strtoupper(md5($signStr));
        $param['sign'] = $sign;

        $content = $this->arrayToXml($param);
        $ret = $this->doPay($content);
        return $ret;
    }

    protected function doPay($data)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_TIMEOUT, 30000);
        curl_setopt($curl, CURLOPT_URL, $this->config['micUrl']);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $res = curl_exec($curl);
        curl_close($curl);
        $ret = $this->xmlToArray($res);
        $this->retmessage = $ret;
        if ($ret['return_code'] == 'SUCCESS' && $ret['result_code'] == 'SUCCESS') {
            return true;
        }
        return false;
    }
}
?>
